/**
 * 
 */
package com.hax2max.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.hax2max.R;
import com.hax2max.control.FriendStalkerException;

/**
 * @author dude
 *
 */
public class LoginViewController extends Activity implements OnClickListener {
    private final int STATUS_SUCCESS = 0;
    private final int STATUS_FAILURE = 1;
    private final Activity activity = this;
    private final Handler mHandler = new LoginHandler();
    private class LoginHandler extends Handler {
	public void handleMessage(Message msg) {
	    switch (msg.what){
	    case STATUS_SUCCESS:
		menuViewController.start(activity, MenuViewController.MAP);
		finish();
		break;
	    case STATUS_FAILURE:
		dialog.dismiss();
		menuViewController.start(activity, MenuViewController.ERRORDIALOG, msg.getData());
		break;
	    }
	}
    }
    
    private MenuViewController menuViewController;
    private ProgressDialog dialog;
    private Context mContext;
    private EditText mUsername;
    private EditText mPassword;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.login);	
	mContext = getBaseContext();
	if (!MenuViewController.isInstance()){
	    menuViewController = MenuViewController.getInstance(mContext);
	    if (menuViewController.checkValidUser()) {
		menuViewController.start(activity, MenuViewController.MAP);
		finish();
	    }
	}
	mUsername = (EditText)findViewById(R.id.LoginViewUsernameEdit);
	mPassword = (EditText)findViewById(R.id.LoginViewPasswordEdit);
	((Button)findViewById(R.id.LoginViewButton)).setOnClickListener(this);

    }

    @Override
    public void onStop(){
	if(dialog != null && dialog.isShowing())
	    dialog.dismiss();
	super.onStop();
    }
    
    public void onClick(View v){
	Thread t = new Thread() {
	    public void run() {
		if (menuViewController == null )
		    menuViewController = MenuViewController.getInstance(mContext);
		try {
		    menuViewController.login(mUsername.getText().toString(),mPassword.getText().toString());
		    mHandler.sendMessage(mHandler.obtainMessage(STATUS_SUCCESS));
		} catch (FriendStalkerException e) {
		    Message m = mHandler.obtainMessage(STATUS_FAILURE);
		    Bundle b = new Bundle(1);
		    b.putInt("errorMessage", e.errorMsgId);
		    m.setData(b);
		    mHandler.sendMessage(m);
		}

	    }
	};
	dialog = ProgressDialog.show(this,"Please wait","logging in...");
	t.start();
    }
}